package ftp;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;

/**
 * @author hubert
 * @date 2018/9/21
 * @description FtpUtil
 */
public class FtpUtil {

	private FTPClient ftpclient;
	private String ipAddress;
	private int ipPort;
	private String userName;
	private String passWord;

	public FtpUtil(String ip, int port, String username, String password) throws
			Exception {
		ipAddress = new String(ip);
		ipPort = port;
		ftpclient = new FTPClient( );
		ftpclient.setDefaultPort(ipPort);
		//ftp编码格式
		ftpclient.setControlEncoding("UTF-8");
		//设置传输超时时间为20s
		ftpclient.setDataTimeout(20*1000);
		//等待结果超时20s
		ftpclient.setSoTimeout(20*1000);
		//链接超时10s
		ftpclient.setConnectTimeout(10*1000);
		//主动模式
		//ftpclient.enterLocalActiveMode();
		//被动模式
		//ftpclient.enterLocalPassiveMode();

		userName = new String(username);
		passWord = new String(password);
		ftpclient.setFileType(FTPClient.BINARY_FILE_TYPE);
		ftpclient.setFileTransferMode( FTPClient.STREAM_TRANSFER_MODE );

	}

	public long getFileSize(String fullFilePath){
		try {
			FTPListParseEngine engine = ftpclient.initiateListParsing(fullFilePath);
			while(engine.hasNext()){
				FTPFile[] files = engine.getNext(5);
				for(int i=0;i<files.length;i++){
					long size = files[i].getSize();
					return size ;
				}
			}
		} catch (IOException ex) {
			System.err.println("getFileSize:"+ex.getMessage()+","+ex);
		}
		return 0L;
	}

	/**
	 * 登录FTP服务器
	 * @throws Exception
	 */
	public void login()  {
		try {
			ftpclient.connect(ipAddress);
			ftpclient.setControlEncoding("gb2312");
			ftpclient.login(userName, passWord);
			//判断是否连接成功
			int reply = ftpclient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)){
				ftpclient.disconnect();
				System.out.println("FTP server refused connection."+reply);
				return ;
			}
		} catch (Exception ex) {
			System.err.println("login:"+ex.getMessage()+","+ex);;
		}
	}

	/**
	 * 退出FTP服务器,先执行logout()，再执行ftpclient.disconnect()
	 * @throws Exception
	 */
	public void logout() {
		try {
			ftpclient.logout();
		} catch (Exception  e) {
			System.err.println("ftpclient.logout:"+e.getMessage()+","+e);
		}finally{
			if (ftpclient.isConnected()) {
				try {
					ftpclient.disconnect();
				} catch(Exception ioe) {
					System.err.println("ftpclient.disconnect:"+ioe.getMessage()+","+ioe);
				}
			}
		}
	}
}
